<?php

namespace App\Services\Account;

use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Relations\HasMany;

class AccountGroupCards 
{
	protected User $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }
   	
   	public function record($cards, $remark, $reason, $data = [])
    {
        DB::transaction(function () use ($cards, $remark, $reason, $data) {

            /**
             * @var User $user
             */
          
            $user = User::lockForUpdate()->find($this->user->id);

            if($remark == "join_group_cards" ||  $remark == 'gift_group_cards'){

            	$cardExpiredAt = Carbon::now()->addDays(cs('sale')->card_expired);
            	for($i = 0;$i < $cards;$i++){

            		$user->groupCards()->create([
            			'remark'=>$remark,
            			'reason'=>$reason,
            			'card_expired_at'=>$cardExpiredAt
            		]);
            	}
            	
            }else{
            	$groupCards = $user->groupCards()->canUsed()->take($cards)->orderBy("id")->update(['is_used'=>true]);

            }

          
        });
    }

    /*---------- plus --------------------------------------------------------------------------------------------------*/

	public function plusGroupCards($cards, $data = [])
	{
		$this->record($cards, 'join_group_cards', '参团成功奖励开团卡', $data);
	}

	public function plusSystemTransferGroupCards($cards, $data = [])
	{
		$this->record($cards, 'gift_group_cards', '系统赠送开团卡', $data);
	}



	/*---------- minus -------------------------------------------------------------------------------------------------*/

	public function minusSystemRecallGroupCards($cards, $data = [])
	{
		$this->record($cards, 'recall_group_cards', '系统回收开团卡', $data);
	}

	public function minusGroupCards($cards, $data = [])
	{
		$this->record($cards, 'use_group_cards', '使用开团卡', $data);
	}


	
}
